package com.inossem.allotin.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextPaint;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.inossem.allotin.R;
import com.inossem.allotin.adapter.input.TransportInputListAdapter;
import com.inossem.allotin.api.LogInApiService;
import com.inossem.allotin.api.TransportInputApiService;
import com.inossem.allotin.bean.login.LogInBean;
import com.inossem.allotin.bean.login.LogInRequestBean;
import com.inossem.allotin.constant.UrlConstant;
import com.inossem.allotin.db.AllotInBean;
import com.inossem.allotin.utils.ACacheUtils;
import com.inossem.allotin.utils.GreenDaoManager;
import com.inossem.allotin.utils.TimeDialogUtil;
import com.inossem.allotin.utils.TimeUtils;
import com.inossem.allotin.utils.ToastUtils;
import com.inossem.allotin.utils.Utils;
import com.inossem.allotin.utils.requestUtils.InossemNewsCallback;
import com.inossem.allotin.utils.requestUtils.RetrofitUtils;
import com.inossem.wms.co.transport.TransportSearchCo;
import com.inossem.wms.vo.BaseObject;
import com.inossem.wms.vo.auth.DicStockLocationAndWhTreeVo;
import com.inossem.wms.vo.transport.TransportHead;
import com.inossem.wms.vo.transport.TransportHeadVo;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import retrofit2.Response;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.inossem.allotin.constant.ItemStatusConstant.DATA;
import static com.inossem.allotin.constant.ItemStatusConstant.LIST_STRING;
import static com.inossem.allotin.constant.ItemStatusConstant.NULL;
import static com.inossem.allotin.constant.ItemStatusConstant.STATUS_DRAFT;
import static com.inossem.allotin.constant.ItemStatusConstant.STATUS_ITEM_FIFTY;
import static com.inossem.allotin.constant.ItemStatusConstant.STATUS_ONE;
import static com.inossem.allotin.constant.ItemStatusConstant.STATUS_ONE_STRING;
import static com.inossem.allotin.constant.ItemStatusConstant.STATUS_ZERO;
import static com.inossem.allotin.constant.ItemStatusConstant.STATUS_ZERO_STRING;
import static com.inossem.allotin.constant.ItemStatusConstant.YEAR_MONTH_DAY;

/**
 * @author LinH
 */
public class TransportInputListActivity extends AppCompatActivity implements View.OnClickListener {
    private int pageIndex = STATUS_ONE;
    private boolean sortAscend = true;
    private boolean isTvTab1 = true;
    private RecyclerView rv;
    private SmartRefreshLayout srl;
    private LinearLayout includeInputNoData;
    private TextView tvTab1, tvInformation, startDate, endDate;
    private TransportInputListAdapter inspectNoticeListAdapter;
    //是否有网络
    private boolean isNetWork = false;
    private ProgressDialog dialog;

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transport_info_list);
        //默认不弹出键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        //全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //强制横屏z
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        GreenDaoManager.getInstance().init(TransportInputListActivity.this);
        dialog = new ProgressDialog(TransportInputListActivity.this);
        dialog.setMessage("正在加载数据...");
        initView();
        initClick();
        isNetWork();
    }

    public void initView() {
        rv = findViewById(R.id.rv);
        srl = findViewById(R.id.srl);
        tvTab1 = findViewById(R.id.tv_tab_1);
        tvInformation = findViewById(R.id.tv_information);
        includeInputNoData = findViewById(R.id.include_input_no_data);
        startDate = findViewById(R.id.startDate);
        endDate = findViewById(R.id.endDate);
        findViewById(R.id.tv_tab_1).setOnClickListener(this);
        findViewById(R.id.tv_return).setOnClickListener(this);
        findViewById(R.id.iv_search).setOnClickListener(this);
        findViewById(R.id.include_input_no_data).setOnClickListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(TransportInputListActivity.this);
        rv.setLayoutManager(layoutManager);
        inspectNoticeListAdapter = new TransportInputListAdapter();
        rv.setAdapter(inspectNoticeListAdapter);
        srl.setEnableAutoLoadMore(false);
        // 是否启用下拉刷新功能
        srl.setEnableRefresh(false);
        // 是否启用上拉加载功能
        srl.setEnableLoadMore(false);
        inspectNoticeListAdapter.setOnItemClickListener(s -> {
            List<TransportHead> list = inspectNoticeListAdapter.getList();
            TransportHead transportHead = list.get(s);
            String listString = new Gson().toJson(transportHead);
            ACacheUtils.setOrderJson(listString);
            Intent intent = new Intent(TransportInputListActivity.this, TransportInputDetailsActivity.class);
//            Bundle b = new Bundle();
//            Gson gson = new Gson();
//            List<TransportHead> list = inspectNoticeListAdapter.getList();
//            TransportHead transportHead = list.get(s);
//            String listString = gson.toJson(transportHead);
//            b.putString(LIST_STRING, listString);
//            b.putString(DATA, STATUS_ONE_STRING);
//            intent.putExtras(b);
            startActivityForResult(intent, 999);
        });
        Utils.setDrawableLeft(findViewById(R.id.tv_return), R.drawable.ic_return_b, STATUS_ITEM_FIFTY, STATUS_ITEM_FIFTY);

        startDate = findViewById(R.id.startDate);
        startDate.setText(TimeUtils.getNowTime("-"));
        startDate.setText(Utils.systemData());
        startDate.setOnClickListener(v1 -> {
            TimeDialogUtil time = new TimeDialogUtil(TransportInputListActivity.this, (year, mouth, day) ->
                    startDate.setText(String.format("%1$d-%2$d-%3$d", year, mouth, day)));
            time.showDialog();
        });
        endDate = findViewById(R.id.endDate);
        endDate.setText(TimeUtils.getNowTime("-"));
        endDate.setText(Utils.systemData());
        endDate.setOnClickListener(v1 -> {
            TimeDialogUtil time = new TimeDialogUtil(TransportInputListActivity.this, (year, mouth, day) ->
                    endDate.setText(String.format("%1$d-%2$d-%3$d", year, mouth, day)));
            time.showDialog();
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 999) {
            if (resultCode == 999) {
                isNetWork();
            }
        }
    }

    private void isNetWork() {
        if (!dialog.isShowing()) {
            dialog.show();
        }
        Utils.isNetWorkAvailableOfGet(UrlConstant.DEFAULT_HTTP + UrlConstant.DEFAULT_DOMAIN + ":" + UrlConstant.DEFAULT_PORT + UrlConstant.DEFAULT_PATH, new Comparable<Boolean>() {
            @Override
            public int compareTo(Boolean available) {
                isNetWork = available;
                if (available) {
                    login();
                    ToastUtils.showToast("有网络");
                } else {
                    offline();
                    ToastUtils.showToast("没有网络");
                }
                return 0;
            }
        });
    }

    private void offline() {
        String start = startDate.getText().toString().trim();
        String end = endDate.getText().toString().trim();
        start = start + " 00:00:00";
        end = end + " 23:59:59";
        List<AllotInBean> list = GreenDaoManager.getInstance().getAllotInBeanList(TimeUtils.transitionStringToData1(start), TimeUtils.transitionStringToData1(end));
        List<TransportHead> headList1 = new ArrayList<>();
        for (AllotInBean allotInBean : list) {
            headList1.add(allotInBean.getMTransportHead());
        }
        if (headList1.size() == STATUS_ZERO) {
            includeInputNoData.setVisibility(VISIBLE);
        } else {
            tvInformation.setText(String.valueOf(headList1.size()));
            includeInputNoData.setVisibility(GONE);
        }
        inspectNoticeListAdapter.addList(headList1);
        if (dialog.isShowing()) {
            dialog.cancel();
        }
    }

    public void initClick() {
        // TextView变粗
        TextPaint paintTvTab1 = tvTab1.getPaint();
        paintTvTab1.setFakeBoldText(true);
    }

    //登录
    private void login() {
        LogInRequestBean requestBean = new LogInRequestBean();
        requestBean.setUserCode("adminsc");
        requestBean.setPassword("123456");
        RetrofitUtils.getRetrofit(TransportInputListActivity.this, getString(R.string.developer_zhanjianyu), getString(R.string.developer_maoyu), getString(R.string.login_module_login), "登录")
                .create(LogInApiService.class)
                .login(requestBean)
                .enqueue(new InossemNewsCallback<BaseObject<LogInBean>>() {
                    @Override
                    public void success(Response<BaseObject<LogInBean>> response) {
                        if (!response.body().getData().getCode().equals("0")) {
                            ToastUtils.showToast("失败");
                            return;
                        }
                        ACacheUtils.setToken(response.body().getData().getToken());
                        getList(NULL, STATUS_ZERO);
                    }

                    @Override
                    public void failure(Response<BaseObject<LogInBean>> response) {
                        ToastUtils.showToast(response.body().getReturnMsg());
                    }
                });
    }

    private void getList(String code, int i) {
        TransportSearchCo bean = new TransportSearchCo();
        bean.setTransportCode(code);
        ArrayList<Integer> list = new ArrayList<>();
        if (isTvTab1) {
            // 草稿 10
            list.add(STATUS_DRAFT);
        }
        String jsonArray = new Gson().toJson(list);
        com.alibaba.fastjson.JSONArray array = com.alibaba.fastjson.JSONArray.parseArray(jsonArray);
        bean.setStatusList(array);
        bean.setSortAscend(sortAscend);
        // stockInputCode单号,CREATE_TIME创建时间
//        bean.setSortColumn(sortColumn);
        bean.setPaging(true);
        String start = startDate.getText().toString().trim();
        String end = endDate.getText().toString().trim();
        bean.setQueryDateStart(TimeUtils.transitionStringToData(start));
        bean.setQueryDateEnd(TimeUtils.transitionStringToData(end));
        bean.setPaging(true);
        bean.setPageSize(Integer.MAX_VALUE);
        bean.setPageIndex(pageIndex);
        getData(bean, i);
    }

    public void getData(TransportSearchCo bean, int i) {
        RetrofitUtils.getRetrofit(TransportInputListActivity.this, getString(R.string.developer_linhao), getString(R.string.developer_shifeng), getString(R.string.transport_info_module_transport_info), getString(R.string.transport_info_module_transport_info))
                .create(TransportInputApiService.class)
                .getTransportList(bean)
                .enqueue(new InossemNewsCallback<BaseObject<TransportHeadVo>>() {
                    @Override
                    public void success(Response<BaseObject<TransportHeadVo>> response) {
                        TransportHeadVo data = response.body().getData();
                        List<TransportHead> headList = data.getHeadlist();
                        for (TransportHead transportHead : headList) {
                            AllotInBean allotInBean = new AllotInBean();
                            allotInBean.setMTransportHead(transportHead);
                            allotInBean.setCreateTime(transportHead.getCreateTime());
                            allotInBean.setStockTransportCode(transportHead.getStockTransportCode());
                            GreenDaoManager.getInstance().addAllotInBean(allotInBean, false);
                        }
                        offline();
                    }
                });
    }

    @Override
    public void onClick(View v) {
        Utils.closeSoftKeyboard(v);
        int i = v.getId();
        if (i == R.id.tv_return) {
            finish();
        } else if (i == R.id.iv_search) {
            String start = startDate.getText().toString().trim();
            String end = endDate.getText().toString().trim();
            Date statd = TimeUtils.transitionStringToData(start);
            Date endd = TimeUtils.transitionStringToData(end);
            if (statd.after(endd)) {
                ToastUtils.showToast(getString(R.string.common_end_bigger_start_time));
                return;
            }
            isNetWork();
        } else if (i == R.id.include_input_no_data) {
            getList(NULL, STATUS_ZERO);
        }
    }
}